<template>
  <div class="app-container">
    <el-row :gutter="20">
      <leftPanel treeType="chapter" @leftClick="getTreeNotes" />
      <el-col :span="20" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
          <el-form-item label="试卷编码" prop="paperCode">
            <el-input v-model="queryParams.paperCode" placeholder="请输入试卷编码" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="试卷名称" prop="paperName">
            <el-input v-model="queryParams.paperName" placeholder="请输入试卷名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="试卷类型" prop="paperType">
            <el-select v-model="queryParams.paperType" placeholder="请输入试卷类型" clearable @keyup.enter.native="handleQuery">
              <el-option v-for="item in questionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="院系" prop="departName">
            <el-input v-model="queryParams.departName" placeholder="请输入院系" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="专业" prop="majorName">
            <el-input v-model="queryParams.majorName" placeholder="请输入专业" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="题库" prop="courseSubject">
            <el-input v-model="queryParams.courseSubject" placeholder="请输入题库" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!--      <el-form-item label="有效截止时间" prop="paperEndTime">-->
          <!--        <el-input-->
          <!--          v-model="queryParams.paperEndTime"-->
          <!--          placeholder="请输入有效截止时间"-->
          <!--          clearable-->
          <!--          @keyup.enter.native="handleQuery"-->
          <!--        />-->
          <!--      </el-form-item>-->
          <el-form-item label="创建人" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!--          <el-form-item label="创建时间" prop="createdTime">-->
          <!--            <el-date-picker v-model="queryParams.createdTime" clearable type="date" value-format="yyyy-MM-dd" placeholder="请选择创建时间">-->
          <!--            </el-date-picker>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['juan:juanPaper:add']" type="primary" plain icon="el-icon-plus" size="mini" :disabled="!queryParams.courseId" @click="handleAdd"
              >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['juan:juanPaper:remove']"
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              >删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              v-hasPermi="['juan:juanPaper:random']"
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="juanPaperList.length > 0 ? false : true"
              @click="handleRandom"
              >随机抽卷
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-hasPermi="['juan:juanPaper:import']" type="warning" plain icon="el-icon-upload2" size="mini" :disabled="!queryParams.courseId" @click="handleImport"
              >导入试卷数据包
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['juan:juanPaper:regroup']"
              type="primary"
              plain
              icon="el-icon-film"
              size="mini"
              :disabled="multiple"
              @click="handleRegroup()"
              >多试卷重组
            </el-button>
          </el-col>
          <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
        </el-row>

        <el-table v-loading="loading" :data="juanPaperList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="试卷名称" width="120" align="center" prop="paperName" show-overflow-tooltip />
          <el-table-column label="试卷编码" width="120" align="center" prop="paperCode" show-overflow-tooltip />
          <el-table-column label="试卷类型" align="center" prop="paperType">
            <template slot-scope="scope">
              <span v-if="scope.row.paperType === '1'">人工组卷</span>
              <span v-else-if="scope.row.paperType === '2'">自动组卷</span>
              <span v-else-if="scope.row.paperType === '3'">人工导入</span>
            </template>
          </el-table-column>
          <el-table-column label="考试时长" align="center" prop="paperTime" />
          <el-table-column label="总分" align="center" prop="paperTotalScore" width="80" />
          <el-table-column label="注意事项" align="center" prop="paperAttention" show-overflow-tooltip />
<!--          <el-table-column label="是否有密封线" align="center" prop="paperSealLine">-->
<!--            <template slot-scope="scope">-->
<!--              <span v-if="scope.row.paperSealLine === '0'">否</span>-->
<!--              <span v-else-if="scope.row.paperSealLine === '1'">是</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="难度系数" align="center" prop="paperEasy">
            <template slot-scope="scope">
              {{ scope.row.paperEasy | floatFormat }}
            </template>
          </el-table-column>
          <!--      <el-table-column label="科目" align="center" prop="paperSubject" />-->
          <!--      <el-table-column label="试卷描述" align="center" prop="paperDes" />-->
          <!--      <el-table-column label="试卷状态" align="center" prop="paperStatus" />-->
          <!--      <el-table-column-->
          <!--        label="有效截止时间"-->
          <!--        align="center"-->
          <!--        prop="paperEndTime"-->
          <!--      />-->
          <el-table-column label="院系" align="center" prop="departName" show-overflow-tooltip />
          <el-table-column label="专业" align="center" prop="majorName" show-overflow-tooltip />
          <el-table-column label="题库" align="center" prop="courseSubject" />
          <el-table-column label="创建人" align="center" prop="userName" />
          <el-table-column label="创建时间" align="center" prop="createdTime" width="170">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" min-width="200">
            <template slot-scope="scope">
              <el-button v-hasPermi="['juan:juanPaper:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:analysis']"
                size="mini"
                type="text"
                icon="el-icon-data-analysis"
                @click="handleAnalysis(scope.row)"
                >数据分析
              </el-button>
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-time"
                @click="handleHistory(scope.row)"
                >历史留存记录
              </el-button> -->
              <el-button
                v-hasPermi="['juan:juanPaper:export']"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleExport(scope.row)"
                >导出EXCEL
              </el-button>
              <el-button
                v-hasPermi="['juan:juanPaper:export']"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleExportJson(scope.row)"
                >导出数据包
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程ID" />
        </el-form-item>
        <el-form-item label="试卷编码" prop="paperCode">
          <el-input v-model="form.paperCode" placeholder="请输入试卷编码" />
        </el-form-item>
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="form.paperName" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="科目" prop="paperSubject">
          <el-input v-model="form.paperSubject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="试卷描述" prop="paperDes">
          <el-input v-model="form.paperDes" placeholder="请输入试卷描述" />
        </el-form-item>
        <el-form-item label="有效截止时间" prop="paperEndTime">
          <el-input v-model="form.paperEndTime" placeholder="请输入有效截止时间" />
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime">
          <el-date-picker clearable
            v-model="form.updatedTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 试卷导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".json"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入json格式文件。</span>
          <!--          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate"-->
          <!--            >下载模板-->
          <!--          </el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 随机抽卷对话框 -->
    <el-dialog :title="'随机抽卷'" :visible.sync="randomOpen" width="55%" append-to-body :before-close="randomClose" class="common-dialog">
      <Random v-if="randomOpen" :course-id="queryParams.courseId" @close="randomClose"></Random>
    </el-dialog>
  </div>
</template>

<script>
import Random from "./random.vue";
import { addJuanPaper, delJuanPaper, listJuanPaper, updateJuanPaper } from "@/api/juan/juanPaper";
import { getToken } from "@/utils/auth";
import { encode } from "js-base64";
import request from "@/utils/request";

export default {
  name: "JuanPaper",
  components: { Random },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      juanPaperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      randomOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: undefined,
        paperCode: undefined,
        paperName: undefined,
        paperType: undefined,
        paperSubject: undefined,
        paperDes: undefined,
        paperStatus: undefined,
        paperEndTime: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
        userName: undefined,
        departName: undefined,
        majorName: undefined,
        courseSubject: undefined,
        paperEasy: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paperId: [{ required: true, message: "租户号不能为空", trigger: "blur" }],
        courseId: [{ required: true, message: "课程ID不能为空", trigger: "blur" }],
        paperCode: [{ required: true, message: "试卷编码不能为空", trigger: "blur" }],
        paperName: [{ required: true, message: "试卷名称不能为空", trigger: "blur" }],
        paperType: [{ required: true, message: "试卷类型不能为空", trigger: "change" }],
        paperSubject: [{ required: true, message: "科目不能为空", trigger: "blur" }],
        paperDes: [{ required: true, message: "试卷描述不能为空", trigger: "blur" }],
        paperStatus: [{ required: true, message: "试卷状态不能为空", trigger: "blur" }],
        paperEndTime: [{ required: true, message: "有效截止时间不能为空", trigger: "blur" }],
        createdBy: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
        createdTime: [{ required: true, message: "创建时间不能为空", trigger: "blur" }],
        updatedBy: [{ required: true, message: "更新人不能为空", trigger: "blur" }],
        updatedTime: [{ required: true, message: "更新时间不能为空", trigger: "blur" }],
      },
      // 试卷导入参数
      upload: {
        // 是否显示弹出层（试卷导入）
        open: false,
        // 弹出层标题（试卷导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: "http://127.0.0.1:8075/juan/juanPaper/importPaperJson",
      },
      questionTypeOptions: [
        {
          value: "1",
          label: "人工组卷",
        },
        {
          value: "2",
          label: "自动组卷",
        },
        {
          value: "3",
          label: "人工导入",
        },
      ],
    };
  },
  created() {},
  methods: {
    // 树节点单击事件
    getTreeNotes(obj) {
      if (obj) {
        this.queryParams.courseId = obj.treeNode.id;
        this.form.courseId = obj.treeNode.id;
        this.handleQuery();
      }else {
        this.queryParams.courseId = undefined;
        this.form.courseId = undefined;
        this.juanPaperList = [];
      }
    },

    /** 查询试卷列表 */
    getList() {
      this.loading = true;
      listJuanPaper(this.queryParams)
        .then((response) => {
          this.juanPaperList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paperId: undefined,
        courseId: undefined,
        paperCode: undefined,
        paperName: undefined,
        paperType: undefined,
        paperSubject: undefined,
        paperDes: undefined,
        paperStatus: "0",
        paperEndTime: undefined,
        paperAttention: undefined,
        paperSealLine: undefined,
        paperTotalScore: undefined,
        paperTime: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paperId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      // this.title = "添加试卷";

      this.$router.push("/juanPaper/juanPaper/add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: "/juanPaper/juanPaper/edit",
        query: {
          paperId: row.paperId,
        },
      });
    },
    /** 数据分析按钮操作 */
    handleAnalysis(row) {
      this.$router.push({
        path: "/juanPaper/juanPaper/analysis",
        query: {
          paperId: row.paperId,
        },
      });
    },
    /** 历史留存记录按钮操作 */
    handleHistory(row) {
      this.$router.push({
        path: "/juanPaper/juanPaper/history",
        query: {
          paperId: row.paperId,
        },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.paperId != null) {
            updateJuanPaper(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addJuanPaper(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperIds = row.paperId || this.ids;
      this.$modal
        .confirm("是否确认删除试卷？")
        .then(() => {
          this.loading = true;
          return delJuanPaper(paperIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport(data) {
      this.download("juan/juanPaper/exportData/" + data.paperId, {}, data.paperName + `.xlsx`);
    },
    /** 导出数据包按钮操作 */
    handleExportJson(data) {
      // this.download('juan/juanPaper/exportPaperJson/' + data.paperId, {}, `juanPaper.json`)
      request({
        url: "juan/juanPaper/exportPaperJson/" + data.paperId,
        method: "post",
      }).then((res) => {
        // this.saveJSON(res, res.juanPaper.paperName + `.json`);
        this.saveJSON(res, data.paperName + `.json`);
      });
    },
    saveJSON(data, filename) {
      if (!data) {
        return;
      }
      if (!filename) {
        filename = "json.json";
      }
      if (typeof data === "object") {
        data = JSON.stringify(data, undefined, 4);
      }
      let blob = new Blob([data], { type: "text/json" });
      let e = document.createEvent("MouseEvents");
      let a = document.createElement("a");
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
      e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      a.dispatchEvent(e);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "试卷导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("juan/juanPaper/importTemplate", {}, `试卷导入模板.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 多试卷重组 */
    handleRegroup() {
      const paperIdstr = this.ids.join(",");
      this.$router.push({
        path: "/juanGenerate/add",
        query: {
          paperIds: encode(paperIdstr),
          courseId: encode(this.queryParams.courseId),
        },
      });
    },

    // 随机抽卷
    handleRandom() {
      this.randomOpen = false;
      this.$nextTick(() => {
        this.randomOpen = true;
      });
      localStorage.removeItem("selection");
    },
    //关闭抽卷弹窗
    randomClose() {
      this.randomOpen = false;
      localStorage.removeItem("selection");
    },
  },
};
</script>
<style lang="scss" scoped>
// el-dialog高度自适应，内容超出时中间出现滚动条
.common-dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
  .el-dialog {
    margin: 0 auto !important;
    position: relative;
    .el-dialog__header {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      width: 100%;
      height: 60px;
      z-index: 1;
    }
    .el-dialog__body {
      width: 100%;
      overflow: hidden;
      overflow-y: auto;
      max-height: 90vh; //最大高度为视口高度的90%
      padding-top: 80px;
      padding-bottom: 100px;
      z-index: 1;
    }
    .el-dialog__footer {
      position: absolute;
      left: 0;
      bottom: 0;
      right: 0;
      width: 100%;
      height: 80px;
      z-index: 1;
    }
  }
}
</style>
